package com.order.itemcategoryproject.utils;

import com.order.itemcategoryproject.pojo.TreeNode;
import com.order.itemcategoryproject.pojo.dArcStaff;
import com.order.itemcategoryproject.pojo.vClassTree;
import com.order.itemcategoryproject.pojo.vClassTreeLan;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Repository
public class parseItemData {

    /**
     * 通过将递归回来的数据添加到节点中
     *
     * @param data
     * @param path
     * @return
     */
    public static TreeNode buildHierarchy(List<vClassTreeLan> data, String path, dArcStaff dArcStaff) {
        TreeNode root = new TreeNode(); // 创建根节点
        List<String> allowedIds = null;
        if ("国内".equals(dArcStaff.getCus_segmentation())) {
            allowedIds = Arrays.asList("10", "11", "12", "14", "15", "16", "17", "18", "19", "20", "28");
        } else if ("国际".equals(dArcStaff.getCus_segmentation())) {
            allowedIds = Arrays.asList("10", "11", "12", "15", "16", "17", "18", "19", "28");
        } else if ("内部".equals(dArcStaff.getCus_segmentation())) {
            allowedIds = Arrays.asList("10", "11", "12", "14", "15", "16", "17", "18", "19", "20", "28");
        }
        for (vClassTreeLan item : data) {
            String[] parts = item.getTreeId().split("\\|");
            TreeNode current = root;

            // 如果第一个元素为空，则跳过，表示当前节点为根节点
            int startIndex = parts[0].isEmpty() ? 1 : 0;
            StringBuilder treeIdBuilder = new StringBuilder(); // 用于构建treeId

            for (int i = startIndex; i < parts.length; i++) {
                String part = parts[i];
                treeIdBuilder.append(part); // 将当前部分添加到treeId中

                // 检查第一个分隔符前的值是否在允许的列表中
                if (i == 0 && !allowedIds.contains(part)) {
                    break; // 如果不在允许的列表中，跳过当前节点
                }

                TreeNode child = findChild(current.getChildren(), part);
                if (child == null) {
                    child = new TreeNode();
                    child.setId(item.getClassId());
                    child.setName(item.getClassName());
                    child.setTreeId(treeIdBuilder.toString()); // 设置节点的treeId

                    if (current.getChildren() == null) {
                        current.setChildren(new ArrayList<>());
                    }
                    current.getChildren().add(child);
                }
                current = child;
                treeIdBuilder.append("|"); // 添加分隔符
            }
        }

        return root;
    }


    /**
     * 添加字节点
     *
     * @param children
     * @param id
     * @return
     */
    private static TreeNode findChild(List<TreeNode> children, String id) {
        if (children != null) {
            for (TreeNode child : children) {
                if (child.getId().equals(id)) {
                    return child;
                }
            }
        }
        return null;
    }
}
